package mark.tom.detector;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.support.annotation.NonNull;
import android.util.Log;

import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

import mark.tom.detector.template.Detector;
import mark.tom.detector.template.Logger;

import static mark.tom.detector.C.FEATURES;
import static mark.tom.detector.Util.checkNull;
import static mark.tom.detector.Util.getLogger;
import static mark.tom.detector.Util.getSHA1DigestByFileName;
import static mark.tom.detector.Util.getSHA256DigestByFileName;

/**
 * @Description: 完整性检测器
 * @Author: ttmk110@163.com
 * @Package: mark.tom.detector
 * @Date: 2020/3/21
 * @Copyright: 版权归 Mark 所有
 * <ModifyLog>
 * @ModifyContent:
 * @Author:
 * @Date: </ModifyLog>
 */
public class IntegrityDetector extends Detector {

    private ApplicationInfo applicationInfo;
    private Logger logger;

    public IntegrityDetector(@NonNull Context context) {
        this(context, false);
    }

    public IntegrityDetector(@NonNull Context context, boolean log) {
        checkNull("context must not be null", context);
        applicationInfo = context.getApplicationInfo();
        logger = getLogger(log);
    }

    @Override
    public boolean check() {
        boolean result = false;
        try {
            result = checkWhEx();
        } catch (Exception ex) {
            logger.log(ex.getMessage(), Log.ERROR);
        }
        return result;
    }

    @Override
    public boolean checkWhEx() throws Exception {
        String sourceDir = applicationInfo.sourceDir;
        JarFile jar = new JarFile(sourceDir);
        Manifest mf = jar.getManifest();
        Map<String, Attributes> mfEntries = mf.getEntries();
        boolean result = true;
        for (String feature : FEATURES) {
            Attributes attr = mfEntries.get(feature);
            if (null == attr) {
                continue;
            }
            logger.log(feature + " Check Start", Log.INFO);
            String sha256Digest = attr.getValue("SHA-256-Digest");
            String sha1Digest = attr.getValue("SHA1-Digest");
            if (null != sha256Digest && sha256Digest.equals(getSHA256DigestByFileName(sourceDir, feature))) {
                logger.log(feature + " Checked With SHA256", Log.DEBUG);
            } else if (null != sha1Digest && sha1Digest.equals(getSHA1DigestByFileName(sourceDir, feature))) {
                logger.log(feature + " Checked With SHA1", Log.DEBUG);
            } else {
                result = false;
                logger.log(feature + " Check Fail", Log.DEBUG);
                logger.log(feature + " Check End", Log.INFO);
                break;
            }
            logger.log(feature + " Check End", Log.INFO);
        }
        return result;
    }

}
